<?php

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

require_once __DIR__ . '/../../vendor/autoload.php';

// 过程化不知道怎么接收消费回调后的返回值
// $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
// $channel = $connection->channel();
// list($queue_name, ,) = $channel->queue_declare('', false, false, true, false);
// $corr_id = uniqid();
// $response = null;
// $onResponse = function ($rep) use($corr_id, &$response) {
// 		if ($rep->get('correlation_id') == $corr_id) {
// 				$response = $rep->body;		
// 		}
// 		// var_dump($response);
// };
// $channel->basic_consume($queue_name, '', false, true, false, false, $onResponse);
// var_dump($response);
// $msg = new AMQPMessage(4, ['correlation_id' => $corr_id, 'reply_to' => $queue_name]);	
// $channel->basic_publish($msg, '', 'rpc');
// while (is_null($response)) {
// 		$channel->wait();
// }
// $channel->close();
// $connection->close();

class FibonacciRpcClient
{
    private $connection;
    private $channel;
    private $callback_queue;
    private $response;
    private $corr_id;

    public function __construct()
    {
        $this->connection = new AMQPStreamConnection(
            'localhost',
            5672,
            'guest',
            'guest'
        );
        $this->channel = $this->connection->channel();
        list($this->callback_queue, ,) = $this->channel->queue_declare(
            "",
            false,
            false,
            true,
            false
        );
        $this->channel->basic_consume(
            $this->callback_queue,
            '',
            false,
            true,
            false,
            false,
            array(
                $this,
                'onResponse'
            )
        );
    }

    public function onResponse($rep)
    {
        if ($rep->get('correlation_id') == $this->corr_id) {
            $this->response = $rep->body;
        }
    }

    public function call($n)
    {
        $this->response = null;
        $this->corr_id = uniqid();

        $msg = new AMQPMessage(
            (string) $n,
            array(
                'correlation_id' => $this->corr_id,
                'reply_to' => $this->callback_queue
            )
        );
        $this->channel->basic_publish($msg, '', 'rpc');
        while (!$this->response) {
            $this->channel->wait();
        }
        return intval($this->response);
    }
}

$fibonacci_rpc = new FibonacciRpcClient();
$response = $fibonacci_rpc->call(2);
echo $response, PHP_EOL;
